package org.beaconframework.maven.mojo;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

/**
 * This maven plugin allows master copies of versioned resources to be tracked in SCM. 
 * @goal execute
 * 
 * @phase generate-sources
 */
public class ResourceTemplateMojo
    extends AbstractMojo
{
	   /**
     * @parameter expression="${project.basedir}"
     */
    private File baseDir;
    /**
     * @parameter default-value="template"
     */
    private String extension;

    public void execute() throws MojoExecutionException {
    	
    	try {
        Collection c = FileUtils.listFiles(baseDir, new String[] { extension },
                false);
        File srcDir = new File(baseDir,"src");
        if (srcDir.isDirectory()) {
        c.addAll(FileUtils.listFiles(srcDir,
                new String[] { extension }, true));
        }
        

        Iterator t = c.iterator();

        while (t.hasNext()) {
            File f = (File) t.next();
            if (!f.isFile()) {
                getLog().warn("Not a file: " + f.getAbsolutePath());
            }

            else {
                String s = f.getAbsolutePath();
                s = s.substring(0, s.lastIndexOf("."));
                File destFile = new File(s);

                if (!destFile.exists()) {
                    getLog().info(
                            "creating resource " + destFile.getAbsolutePath());

                    try {
                        FileUtils.copyFile(f, destFile);
                    } catch (IOException e) {
                        throw new MojoExecutionException("error copying file",
                                e);
                    }
                } else {
                    getLog().info(
                            "not creating " + destFile.getAbsolutePath()
                                    + " because it already exists");
                }

            }
        }
    	}
    	catch (RuntimeException e) {
    		getLog().error("error processing template resources", e);
    	}

    }

}
